package cn.ddd.linktran.infrastructure.record.gateway;

import cn.ddd.linktran.domain.domainobject.VisitStatisticsDO;
import cn.ddd.linktran.domain.gateway.VisitStatisticsGateWay;
import cn.ddd.linktran.infrastructure.record.convertor.VisitStatisticsConvertor;
import cn.ddd.linktran.infrastructure.record.mapper.VisitStatisticsMapper;
import cn.ddd.linktran.infrastructure.record.po.VisitStatistics;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class VisitStatisticsGateWayImpl implements VisitStatisticsGateWay {
    @Autowired
    private VisitStatisticsMapper visitStatisticsMapper;
    @Autowired
    private VisitStatisticsConvertor visitStatisticsConvertor;
    @Override
    public VisitStatisticsDO selectByUniqueKey(Date statisticsDate, String compressionCode, String shortUrl, String longUrl) {
        LambdaQueryWrapper<VisitStatistics> qw = Wrappers.<VisitStatistics>lambdaQuery()
                .eq(VisitStatistics::getStatisticsDate, statisticsDate)
                .eq(VisitStatistics::getCompressionCode, compressionCode)
                .eq(VisitStatistics::getShortUrl, shortUrl)
                .eq(VisitStatistics::getLongUrl, longUrl)
                .last("LIMIT 1");

        List<VisitStatistics> list = visitStatisticsMapper.selectList(qw);
        return list.isEmpty() ? null : visitStatisticsConvertor.toDO(list.get(0));
    }

    @Override
    public int insertVisitStatisticsDO(VisitStatisticsDO visitStatisticsDO) {
        return visitStatisticsMapper.insert(visitStatisticsConvertor.toPO(visitStatisticsDO));
    }

    @Override
    public int updateByPrimaryKeySelective(VisitStatisticsDO visitStatisticsDO) {
        return visitStatisticsMapper.updateById(visitStatisticsConvertor.toPO(visitStatisticsDO));
    }
}
